package com.ljyanimo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ljyanimo.entity.SysMenuRole;
import com.ljyanimo.entity.SysRole;
import com.ljyanimo.entity.SysUserRole;
import com.ljyanimo.mapper.SysRoleMapper;
import com.ljyanimo.mapper.SysUserRoleMapper;
import com.ljyanimo.response.ServerResponse;
import com.ljyanimo.service.ISysMenuRoleService;
import com.ljyanimo.service.ISysRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ljyanimo.service.ISysUserRoleService;
import com.ljyanimo.vo.SaveRoleVo;
import com.ljyanimo.vo.UpdateRoleVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;

import java.util.ArrayList;
import java.util.List;
/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author
 * @since 2020-10-16
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements ISysRoleService {

    @Autowired
    private ISysMenuRoleService iSysMenuRoleService;

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public ServerResponse save(SaveRoleVo saveRoleVo) {
        SysRole sysRole = new SysRole();
        BeanUtils.copyProperties(saveRoleVo,sysRole);
        sysRole.setCreateTime(LocalDateTime.now());
        baseMapper.insert(sysRole);
        iSysMenuRoleService.saveBatch(getSysMenuRoleList(saveRoleVo.getAuthids(),sysRole.getId()));
        return ServerResponse.createBySuccess();
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public ServerResponse update(UpdateRoleVo updateRoleVo) {
        SysRole result = baseMapper.selectById(updateRoleVo.getId());
        if(result == null){
            return ServerResponse.createByError("数据不存在");
        }
        SysRole sysRole = new SysRole();
        BeanUtils.copyProperties(updateRoleVo,sysRole);
        baseMapper.updateById(sysRole);


        iSysMenuRoleService.remove(new QueryWrapper<SysMenuRole>().eq("role_id", updateRoleVo.getId()));

        iSysMenuRoleService.saveBatch(getSysMenuRoleList(updateRoleVo.getAuthids(),updateRoleVo.getId()));

        return ServerResponse.createBySuccess();
    }

    private List<SysMenuRole> getSysMenuRoleList(String[] authids,Integer roleId){
        List<SysMenuRole> list = new ArrayList<>();
        for(String id : authids){
            SysMenuRole sysMenuRole = new SysMenuRole();
            sysMenuRole.setMenuId(Integer.valueOf(id));
            sysMenuRole.setRoleId(roleId);
            list.add(sysMenuRole);
        }
        return list;
    }
}
